package com.ysu.zyw.controller;

import com.ysu.zyw.modal.dto.BlogLeavingMessageInformation;
import com.ysu.zyw.modal.dto.BlogRegisterInformation;
import com.ysu.zyw.other.exception.KnownException;
import com.ysu.zyw.service.BlogPromptService;
import com.ysu.zyw.service.BlogUserService;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * Created by zhang_yao_wu1993 on 15/4/24.
 *
 * @author by Zerur
 */
@Controller
public class BlogUserController {
    private BlogPromptService blogPromptService;
    private BlogUserService blogUserService;

    public BlogPromptService getBlogPromptService() {
        return blogPromptService;
    }

    @Resource(name = "blogPromptService")
    public void setBlogPromptService(BlogPromptService blogPromptService) {
        this.blogPromptService = blogPromptService;
    }

    public BlogUserService getBlogUserService() {
        return blogUserService;
    }

    @Resource(name = "blogUserService")
    public void setBlogUserService(BlogUserService blogUserService) {
        this.blogUserService = blogUserService;
    }



    @RequestMapping("/Register")
    public String register(@Valid BlogRegisterInformation blogRegisterInformation, BindingResult result) {
        if(result.hasErrors()) {
            throw new KnownException("信息有误 请重新注册");
        }

        blogUserService.register(blogRegisterInformation);
        return "SuccessPromptPage";
    }



    @ExceptionHandler(AccessDeniedException.class)
    public ModelAndView handlerAccessDeniedException(AccessDeniedException e) {
        e.printStackTrace();
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/view/blog_Prompt.jsp");
        blogPromptService.fillInsufficientPermissionsModelAndView(modelAndView);
        return modelAndView;
    }

    @ExceptionHandler(KnownException.class)
    public ModelAndView handlerKnownException(KnownException e) {
        e.printStackTrace();
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/view/blog_Prompt.jsp");
        blogPromptService.fillKnownExceptionPromptModelAndView(modelAndView, e);
        return modelAndView;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handlerUnknownException(Exception e) {
        e.printStackTrace();
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/view/blog_Prompt.jsp");
        blogPromptService.fillUnknownExceptionPromptModelAndView(modelAndView);
        return modelAndView;
    }
}